package com.example.shop_2304.search

import android.graphics.Color
import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.widget.TextView
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity
import androidx.appcompat.widget.SearchView
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import androidx.recyclerview.widget.GridLayoutManager
import com.alibaba.android.arouter.facade.annotation.Autowired
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.blankj.utilcode.util.SPUtils
import com.blankj.utilcode.util.ToastUtils
import com.example.base.mvvm.BaseActivity
import com.example.shop_2304.R
import com.example.shop_2304.adapter.GoodMutilAdapter
import com.example.shop_2304.databinding.ActivitySearchBinding
import com.example.shop_2304.room.AppDbUtils
import com.example.shop_2304.room.HistoryEntity
import com.google.android.material.chip.Chip

/**
 * 搜索页面  输入关键词后 回车或者点击搜索文字，实现搜索出指定商品 ，将关键词进行保存并展示
 */
@Route(path = "/app/SearchActivity")
class SearchActivity : BaseActivity<ActivitySearchBinding,SearchViewModel>() {
    @Autowired
    @JvmField
    var cid:Int = 0
    @Autowired
    @JvmField
    var cname:String = ""
    var keyword:String = ""
    var limit:Int = 10
    var news:Boolean = false
    var page:Int = 1
    var priceOrder:String = ""
    var salesOrder:String = ""

    lateinit var goodMutilAdapter: GoodMutilAdapter
    override fun initView() {
        ARouter.getInstance().inject(this)

        binding.tvCname.text = cname

        viewModel.goods(cid, keyword, limit, news, page, priceOrder, salesOrder)

        goodMutilAdapter = GoodMutilAdapter()
        binding.rvGoods.adapter = goodMutilAdapter
        binding.rvGoods.layoutManager = GridLayoutManager(this,2)
        //查询历史搜索数据
        queryHis()
        binding.sv.setOnQueryTextListener(object:SearchView.OnQueryTextListener{
            override fun onQueryTextSubmit(query: String?): Boolean {
                //按回车 会触发
                if(query!=null){
                    keyword = query
                    //请求数据
                    viewModel.goods(cid, keyword, limit, news, page, priceOrder, salesOrder)
                    AppDbUtils.getDb().getHisDao().insert(HistoryEntity(query,SPUtils.getInstance().getString("phone")))
                    //实时看到关键词变化
                    queryHis()
                }

                return false
            }

            override fun onQueryTextChange(newText: String?): Boolean {
               //文字发生变化后就触发 //实时搜索
                if (newText != null) {
                    keyword = newText
                    viewModel.goods(cid, keyword, limit, news, page, priceOrder, salesOrder)
                }
                return false
            }
        })
        binding.tvSearch.setOnClickListener {
            AppDbUtils.getDb().getHisDao().deleteAll()
            binding.cg.removeAllViews()
        }
        //点击新品，，查询新品数据
        binding.tvIsNew.setOnClickListener {
            if(news){//是选中状态   未选中
                news = false
                binding.tvIsNew.setTextColor(Color.BLACK)
            }else{
                //未选中状态   点击之后变成选中状态  文字变成红色
                news = true
                binding.tvIsNew.setTextColor(Color.RED)
            }
            viewModel.goods(cid, keyword, limit, news, page, priceOrder, salesOrder)
        }
        //点击价格  实现价格排序  默认价格是无序  点击第一下 升序  第几第二下  降序   点击第三下  无序
        binding.ivPrice.setOnClickListener {
            if(priceOrder==""){
                priceOrder = "asc"
                binding.ivPrice.setImageResource(R.drawable.sort1)
            }else if(priceOrder=="asc"){
                priceOrder = "desc"
                binding.ivPrice.setImageResource(R.drawable.sort2)
            }else if(priceOrder=="desc"){
                priceOrder=""
                binding.ivPrice.setImageResource(R.drawable.sort3)
            }
            //当按照价格排序时   销量一定是无序的
            salesOrder = ""
            binding.ivSale.setImageResource(R.drawable.sort3)

            viewModel.goods(cid, keyword, limit, news, page, priceOrder, salesOrder)
        }
        //点击销量  实现价格排序  默认价格是无序  点击第一下 升序  第几第二下  降序   点击第三下  无序
        binding.ivSale.setOnClickListener {
            if(salesOrder==""){
                salesOrder = "asc"
                binding.ivSale.setImageResource(R.drawable.sort1)
            }else if(salesOrder=="asc"){
                salesOrder = "desc"
                binding.ivSale.setImageResource(R.drawable.sort2)
            }else if(salesOrder=="desc"){
                salesOrder=""
                binding.ivSale.setImageResource(R.drawable.sort3)
            }
            //当按照价格排序时   销量一定是无序的
            priceOrder = ""
            binding.ivPrice.setImageResource(R.drawable.sort3)

            viewModel.goods(cid, keyword, limit, news, page, priceOrder, salesOrder)
        }
        //点击商品，跳转到详情界面
        goodMutilAdapter.setOnItemClickListener { adapter, view, position ->
            ARouter.getInstance().build("/app/XqDetailActivity").withInt("gid",goodMutilAdapter.data[position].id).navigation()
        }
    }

    private fun queryHis() {
        //查询数据库
        val list = AppDbUtils.getDb().getHisDao().query(SPUtils.getInstance().getString("phone"))
        //动态添加chip  创建chip 将chip放到布局中
        if(list.size>0){
            //先将之前展示的进行清空
            binding.cg.removeAllViews()
            list.reverse()//将数据旋转
            list.forEach {
                val chip = LayoutInflater.from(this).inflate(R.layout.item_cg, null) as Chip
                //将chip中的text设置上内容
                chip.findViewById<TextView>(R.id.name).text = it.keyword
                //将chip添加到cg中
                binding.cg.addView(chip)

                //点击chip控件，searchView上显示对应内容
                chip.setOnClickListener { it1->
                    binding.sv.setQuery(it.keyword,true)
                }
                //点击chip上的关闭图标，可以将数据删除
                chip.setOnCloseIconClickListener { it2->
                    //先删后台 在删页面
                    AppDbUtils.getDb().getHisDao().delete(it)
                    //页面删除
                    binding.cg.removeView(it2)
                }
            }
        }
    }

    override fun initData() {
            viewModel.goodsSuccess.observe(this){
                if(it.code==200){
                    //多布局  type需要我们手动更新
                    it.data.list.forEachIndexed { index, goods ->
                        goods.type = index%2
                    }
                    goodMutilAdapter.data.clear()
                    goodMutilAdapter.data.addAll(it.data.list)
                    goodMutilAdapter.notifyDataSetChanged()
                }else{
                    ToastUtils.showLong(it.message)
                }
            }
    }

    override fun getViewModel(): Class<SearchViewModel> = SearchViewModel::class.java

    override fun getLayout(): Int  = R.layout.activity_search

}